import java.util.Map;

// 1. 抽象表达式接口
interface PermissionExpression {
    boolean interpret(Map<String, String> context); // 上下文含用户信息
}

// 2. 终结符表达式：基础条件（如角色、部门）
class TerminalExpression implements PermissionExpression {
    private String key;
    private String value;

    public TerminalExpression(String rule) {
        String[] parts = rule.split(":"); // 解析"key:value"
        this.key = parts[0].trim();
        this.value = parts[1].trim();
    }

    @Override
    public boolean interpret(Map<String, String> context) {
        return context.get(key) != null && context.get(key).equals(value);
    }
}

// 3. 非终结符表达式：AND逻辑
class AndExpression implements PermissionExpression {
    private PermissionExpression expr1;
    private PermissionExpression expr2;

    public AndExpression(PermissionExpression expr1, PermissionExpression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    @Override
    public boolean interpret(Map<String, String> context) {
        return expr1.interpret(context) && expr2.interpret(context);
    }
}

// 4. 非终结符表达式：OR逻辑
class OrExpression implements PermissionExpression {
    private PermissionExpression expr1;
    private PermissionExpression expr2;

    public OrExpression(PermissionExpression expr1, PermissionExpression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    @Override
    public boolean interpret(Map<String, String> context) {
        return expr1.interpret(context) || expr2.interpret(context);
    }
}

public class Main {
    public static void main(String[] args) {
        // 用户上下文数据
        Map<String, String> user = Map.of(
                "role", "editor",
                "department", "marketing",
                "level", "4"
        );

        // 手动构建规则树：role:editor OR (department:marketing AND level > 3)
        PermissionExpression rule = new OrExpression(
                new TerminalExpression("role:editor"),
                new AndExpression(
                        new TerminalExpression("department:marketing"),
                        new TerminalExpression("level:4") // 实际需扩展比较操作符解析
                )
        );

        System.out.println("权限检查结果: " + rule.interpret(user)); // 输出 true
    }
}
